package com.xingda.packing.dmss.led.impl;

import com.xingda.packing.dmss.led.LedConnService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.Socket;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class LedConnServiceImpl implements LedConnService {

	@Override
	public Socket getConn(String ip, int port) {
		return alwaysConn(ip, port);
	}

	private Socket alwaysConn(String ip, int port) {
		Socket socket = null;
		int i = 0;
		while (socket == null && i < 5) {
			try {
				log.info("连接Socket,IP-{},port-{}", ip, port);
				socket = new Socket(ip, port);
				log.info("====socket:{}", socket);
			} catch (Exception e) {
				log.info("第i:{}次连接Socket失败,IP-{},port-{}", i, ip, port);
				e.printStackTrace();
				try {
					TimeUnit.MILLISECONDS.sleep(1000);
				} catch (InterruptedException e1) {
					log.info("LED重新连接线程被中断");
					e1.printStackTrace();
				}
			} finally {
				i++;
			}
		}
		return socket;
	}

}
